"""
WVP-Pro集成API端点
"""
from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from datetime import datetime
from core.database import get_db
from services.wvp_integration_service import WVPIntegrationService
from services.sync_scheduler import get_sync_scheduler
from utils.response import APIResponse
import structlog

logger = structlog.get_logger(__name__)
router = APIRouter()


def get_wvp_service(db: Session = Depends(get_db)) -> WVPIntegrationService:
    """获取WVP-Pro集成服务实例"""
    return WVPIntegrationService(db)


@router.get("/test", response_model=APIResponse[Dict[str, Any]])
async def test_wvp_connection(
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    测试WVP-Pro连接
    """
    try:
        is_connected = await service.test_wvp_connection()
        
        if is_connected:
            server_info = await service.get_wvp_server_info()
            return APIResponse(
                code=200,
                message="WVP-Pro连接成功",
                data={
                    "connected": True,
                    "server_info": server_info
                }
            )
        else:
            return APIResponse(
                code=200,
                message="WVP-Pro连接失败",
                data={
                    "connected": False,
                    "server_info": {}
                }
            )
            
    except Exception as e:
        logger.error("WVP-Pro连接测试异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="连接测试失败"
        )


@router.post("/sync", response_model=APIResponse[Dict[str, int]])
async def sync_devices_from_wvp(
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    从WVP-Pro同步设备信息
    """
    try:
        result = await service.sync_devices_from_wvp()
        
        return APIResponse(
            code=200,
            message="设备同步完成",
            data=result
        )
        
    except Exception as e:
        logger.error("WVP-Pro设备同步异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="设备同步失败"
        )


@router.post("/sync/batch", response_model=APIResponse[Dict[str, int]])
async def batch_sync_devices(
    device_ids: List[str],
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    批量同步指定设备
    """
    try:
        if not device_ids:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="设备ID列表不能为空"
            )
        
        result = await service.batch_sync_cameras(device_ids)
        
        return APIResponse(
            code=200,
            message="批量设备同步完成",
            data=result
        )
        
    except Exception as e:
        logger.error("WVP-Pro批量设备同步异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="批量设备同步失败"
        )


@router.post("/status/update", response_model=APIResponse[Dict[str, int]])
async def update_camera_status(
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    从WVP-Pro更新摄像头状态
    """
    try:
        result = await service.update_camera_status_from_wvp()
        
        return APIResponse(
            code=200,
            message="摄像头状态更新完成",
            data=result
        )
        
    except Exception as e:
        logger.error("WVP-Pro摄像头状态更新异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="摄像头状态更新失败"
        )


@router.get("/devices", response_model=APIResponse[List[Dict]])
async def get_wvp_devices(
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    获取WVP-Pro设备列表
    """
    try:
        devices = await service.get_wvp_device_list()
        
        return APIResponse(
            code=200,
            message="获取WVP-Pro设备列表成功",
            data=devices
        )
        
    except Exception as e:
        logger.error("获取WVP-Pro设备列表异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取设备列表失败"
        )


@router.get("/devices/{device_id}/channels", response_model=APIResponse[List[Dict]])
async def get_device_channels(
    device_id: str,
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    获取WVP-Pro设备通道列表
    """
    try:
        channels = await service.get_wvp_device_channels(device_id)
        
        return APIResponse(
            code=200,
            message="获取设备通道列表成功",
            data=channels
        )
        
    except Exception as e:
        logger.error("获取WVP-Pro设备通道异常", device_id=device_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取设备通道失败"
        )


@router.get("/cameras/{camera_id}/stream", response_model=APIResponse[Dict[str, str]])
async def get_camera_stream_url(
    camera_id: int,
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    获取摄像头视频流地址
    """
    try:
        stream_url = await service.get_stream_url(camera_id)
        
        if stream_url:
            return APIResponse(
                code=200,
                message="获取视频流地址成功",
                data={"stream_url": stream_url}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="无法获取视频流地址"
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error("获取视频流地址异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取视频流地址失败"
        )


@router.get("/cameras/{camera_id}/playback", response_model=APIResponse[Dict[str, str]])
async def get_camera_playback_url(
    camera_id: int,
    start_time: datetime = Query(..., description="开始时间"),
    end_time: datetime = Query(..., description="结束时间"),
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    获取摄像头录像回放地址
    """
    try:
        if start_time >= end_time:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="开始时间必须早于结束时间"
            )
        
        playback_url = await service.get_playback_url(camera_id, start_time, end_time)
        
        if playback_url:
            return APIResponse(
                code=200,
                message="获取录像回放地址成功",
                data={"playback_url": playback_url}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="无法获取录像回放地址"
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error("获取录像回放地址异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取录像回放地址失败"
        )


@router.post("/cameras/{camera_id}/ptz", response_model=APIResponse[bool])
async def control_camera_ptz(
    camera_id: int,
    command: str = Query(..., description="PTZ控制命令"),
    horizontal_speed: int = Query(50, ge=1, le=100, description="水平速度"),
    vertical_speed: int = Query(50, ge=1, le=100, description="垂直速度"),
    zoom_speed: int = Query(50, ge=1, le=100, description="缩放速度"),
    service: WVPIntegrationService = Depends(get_wvp_service)
):
    """
    PTZ控制
    """
    try:
        success = await service.control_ptz(
            camera_id, command, horizontal_speed, vertical_speed, zoom_speed
        )
        
        if success:
            return APIResponse(
                code=200,
                message="PTZ控制成功",
                data=True
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="PTZ控制失败"
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error("PTZ控制异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="PTZ控制失败"
        )


# 同步调度器相关接口
@router.get("/scheduler/status", response_model=APIResponse[Dict[str, Any]])
async def get_scheduler_status():
    """
    获取同步调度器状态
    """
    try:
        scheduler = get_sync_scheduler()
        status_info = scheduler.get_status()
        
        return APIResponse(
            code=200,
            message="获取调度器状态成功",
            data=status_info
        )
        
    except Exception as e:
        logger.error("获取调度器状态异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取调度器状态失败"
        )


@router.post("/scheduler/start", response_model=APIResponse[bool])
async def start_scheduler():
    """
    启动同步调度器
    """
    try:
        scheduler = get_sync_scheduler()
        await scheduler.start()
        
        return APIResponse(
            code=200,
            message="同步调度器启动成功",
            data=True
        )
        
    except Exception as e:
        logger.error("启动同步调度器异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="启动同步调度器失败"
        )


@router.post("/scheduler/stop", response_model=APIResponse[bool])
async def stop_scheduler():
    """
    停止同步调度器
    """
    try:
        scheduler = get_sync_scheduler()
        await scheduler.stop()
        
        return APIResponse(
            code=200,
            message="同步调度器停止成功",
            data=True
        )
        
    except Exception as e:
        logger.error("停止同步调度器异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="停止同步调度器失败"
        )


@router.post("/scheduler/sync", response_model=APIResponse[Dict[str, Any]])
async def force_sync():
    """
    强制执行一次同步
    """
    try:
        scheduler = get_sync_scheduler()
        result = await scheduler.force_sync()
        
        return APIResponse(
            code=200,
            message="强制同步完成",
            data=result
        )
        
    except Exception as e:
        logger.error("强制同步异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="强制同步失败"
        )


@router.post("/scheduler/status-update", response_model=APIResponse[Dict[str, Any]])
async def force_status_update():
    """
    强制执行一次状态更新
    """
    try:
        scheduler = get_sync_scheduler()
        result = await scheduler.force_status_update()
        
        return APIResponse(
            code=200,
            message="强制状态更新完成",
            data=result
        )
        
    except Exception as e:
        logger.error("强制状态更新异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="强制状态更新失败"
        )